<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="机器人编号" prop="robotCode">
        <el-input v-model="formData.robotCode" placeholder="请输入机器人编号" />
      </el-form-item>
      <el-form-item label="销售合同编号" prop="saleNo">
        <el-input v-model="formData.saleNo" placeholder="请输入销售合同编号" />
      </el-form-item>

      <el-form-item label="延保信息" prop="extendInfo">
        <el-input v-model="formData.extendInfo" placeholder="请输入延保信息" />
      </el-form-item>
      <!-- 新增质保相关字段 -->
      <el-form-item label="质保起始日期" prop="startDate">
        <el-date-picker
          v-model="formData.startDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择起始日期"
          @change="calcEndDate"
        />
      </el-form-item>

      <el-form-item label="质保周期(月)" prop="warrantyPeriod">
        <el-input-number
          v-model="formData.warrantyPeriod"
          :min="1"
          :max="120"
          :step="1"
          controls-position="right"
          @change="calcEndDate"
        />
      </el-form-item>

      <el-form-item label="质保截止日期" prop="endDate">
        <el-date-picker
          v-model="formData.endDate"
          type="date"
          value-format="YYYY-MM-DD"
          disabled
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RobotApi, RobotVO } from "@/api/health/robot";

/** 机器人 表单 */
defineOptions({ name: "RobotForm" });

const { t } = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const formData = ref({} as any);
const formRef = ref(); // 表单 Ref
const formRules = reactive({
  robotCode: [
    { required: true, message: "机器人编号不能为空", trigger: "blur" },
  ],
  saleNo: [
    { required: true, message: "销售合同编号不能为空", trigger: "blur" },
  ],
  extendInfo: [
    { required: true, message: "延保信息不能为空", trigger: "blur" },
  ],
});
import dayjs from "dayjs";

/* …… 原有代码保持不变 …… */

/** 计算质保截止日期 */
const calcEndDate = () => {
  if (!formData.value.startDate || !formData.value.warrantyPeriod) {
    formData.value.endDate = "";
    return;
  }
  // dayjs 的 add 方法，月为单位
  formData.value.endDate = dayjs(formData.value.startDate)
    .add(formData.value.warrantyPeriod, "month")
    .format("YYYY-MM-DD");
};
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await RobotApi.getRobot(id);
    } finally {
      formLoading.value = false;
    }
  } else {
    // 新增时给质保周期默认值 12 个月
    formData.value.warrantyPeriod = 12;
    // 如果后端接口返回了合同签订日期，可直接赋值
    // formData.value.startDate = formData.value.contractSignDate ?? ''
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as RobotVO;
    if (formType.value === "create") {
      if (formData.value.city == "市辖区") {
        formData.value.city = formData.value.district;
        formData.value.district = undefined;
      }
      await RobotApi.createRobot(data);
      message.success(t("common.createSuccess"));
    } else {
      if (formData.value.city == "市辖区") {
        formData.value.city = formData.value.district;
        formData.value.district = undefined;
      }
      await RobotApi.updateRobot(data);
      message.success(t("common.updateSuccess"));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    robotCode: "",
    saleNo: "",
    extendInfo: "",
    startDate: "",
    warrantyPeriod: 12,
    endDate: "",
  };
  nextTick(() => formRef.value?.clearValidate());
  formRef.value?.resetFields();
};
</script>
